﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using OgilvyOne.Ext.Weibo.Common;
using OgilvyOne.Ext.Weibo.Configuration;
using OgilvyOne.Ext.Weibo.Lib;
using OgilvyOne.Golf.Model;
using OgilvyOne.Golf.DAL;
using OgilvyOne.Golf.IDAL;
using System.Text;
using System.Data;
using ECCIT;
using ECCIT.Data;
using System.IO;
using System.Xml;
using OgilvyOne.Ext.Weibo.Model;
namespace Golf
{
    using Environment_v2 = OgilvyOne.Ext.Weibo.Configuration.Environment;
    using OAuthAccessToken_v2 = OgilvyOne.Ext.Weibo.Common.OAuthAccessToken;
    using Microblog_v2 = OgilvyOne.Ext.Weibo.Lib.Microblog;
    using UserInfo_v2 = OgilvyOne.Ext.Weibo.Model.UserInfo;
    using Users_v2 = OgilvyOne.Ext.Weibo.Model.Users;
    using MicroblogException_v2 = OgilvyOne.Ext.Weibo.Common.MicroblogException;
    using Source_v2 = OgilvyOne.Ext.Weibo.Model.Source;
    using System.Xml.Serialization;
    
    public partial class GateService : System.Web.UI.Page
    {
        const int Pagesize =3000;
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/xml";
            Response.ContentEncoding = Encoding.UTF8;
            try
            {
                string op = Request.Params["op"];
                Session["paIndex"] = 0;

                if (op == "0")
                {
                    savLogin();
                }
                if (op == "1")
                {
                    if (Session["weibo"] != null)
                    {
                        if (Session["HaveF"] == null)
                        {
                            GetMyFansFromSina();
                        }

                        Weiboinfo usm = Session["weibo"] as Weiboinfo;
                        if (Session["weibo"] != null)
                        {
                            if (Request["key"] != null)
                            {
                                string key = Request["key"].ToString();
                                Response.Write(GetMyFansFromDB(usm.WeiboUID, key));
                            }
                            else
                            {
                                Response.Write(GetMyFansFromDB(usm.WeiboUID, null));
                            }
                        }
                    }
                }

                if (op == "2")
                {
                    if (Session["weibo"] != null)
                    {
                        Stream stre = Request.InputStream;
                        GXML(stre);
                    }
                }

                //验证是否登陆
                if (op == "get_session")
                {
                    string key = Request.Params["key"];
                    var reslut = Session[key];
                    string s = reslut != null ? "1" : "0";
                    Response.Write(string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?><result>{0}</result>", s));
                }

                if (Request["cmd"] != null)
                {
                    var reslut = Session["weibo"];
                    string s = reslut != null ? "1" : "0";
                    Response.Write(s);
                }
            }
            catch (Exception ex)
            {
                Response.Write(string.Format("<?xml version=\"1.0\"?><error>{0}</error>", ex.Message));
                Response.End();
            }
        }
        /// <summary>
        /// 登陆并保存
        /// </summary>
        public void savLogin()
        {
            object o = Request.QueryString["access_token"];
            if (o == null) throw new ArgumentNullException("access_token");
            string accessToken = (string)o;
            OAuthAccessToken_v2 token = new OAuthAccessToken_v2();
            token.Token = accessToken;
            // 写session
            string sUserID = Request["uid"];
            Weiboinfo wb = new Weiboinfo();
            wb.WeiboToken = token;
            wb.WeiboUID = sUserID;
            wb.IsHavenLg = true;
            Session["weibo"] = wb;
           
            Int64 uid; 
            Int64.TryParse(sUserID, out uid);
            UserInfo_v2 user= Microblog_v2.GetUserInfo(token, uid);
            IDALuser iusr = new UserDAL();
            UserModel usemod = new UserModel();
            usemod.MyUID = user.ID.ToString();
            usemod.MyScreenName = user.ScreenName;
            usemod.MyProImage = user.ProfileImageUrl;
            usemod.MyAvatarImage = user.AvatarLarge;          
            string output;
            output = iusr.ADD(usemod).Result?"1":"0";
            Session.Remove("HaveF");
            Response.Write(output);
        }

        /// <summary>
        /// 获取粉丝
        /// </summary>
        public void  GetMyFansFromSina()
        {
            Users_v2 users = new Users_v2();
            int pageIndex = 1;
            Weiboinfo wb = new Weiboinfo();
            wb = (Session["weibo"] as Weiboinfo);
            int count = 200;
            while (true)
            {
                long ii = Convert.ToInt64(wb.WeiboUID);
                Users_v2 temp = Microblog_v2.GetBilateralFriendUsers(wb.WeiboToken, ii, count, pageIndex, null);
                foreach (UserInfo_v2 user in temp.Items)
                {
                    users.Items.Add(user);
                }
                if (temp.Items.Count < count) break;
                pageIndex++;
            }
            
            IDALfans ifans = new MyFansDAL();
            StringBuilder stb = new StringBuilder();
            List<MyFansModel> mfml = new List<MyFansModel>();
            foreach (UserInfo_v2 vv in users.Items)
            {
                MyFansModel mfm = new MyFansModel();
                mfm.FansUID = vv.ID.ToString();
                mfm.FansScreenName = vv.ScreenName;
                mfm.FansProImageUrl = vv.ProfileImageUrl;
                mfm.FansAvatarLarge = vv.AvatarLarge;
                mfm.MyUID = wb.WeiboUID;
               
                mfml.Add(mfm);
            }

            ifans.ADD(mfml);
            Session["HaveF"] = true;
        }
        
        public string GetMyFansFromDB(string uid,string key)
        {
            string result = string.Empty;
            var cachekey = uid + (string.IsNullOrEmpty(key) ? "" : key);
            if (DataCache.GetCache(cachekey) == null)
            {
                result = GetXML(uid, key, 0);
                DataCache.SetCache(cachekey, result);
            }
            else
            {
                result = DataCache.GetCache(cachekey).ToString();
            }
            return result;
            //return GetXML(uid, key, 0);
        }

        /// <summary>
        /// 从DB中读取粉丝
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="key"></param>
        /// <param name="currpage"></param>
        /// <returns></returns>
        private static string GetXML(string uid, string key, int currpage)
        {
            PagingParameter pagpar = PagingParameterFactory.CreateInstance(true, currpage, Pagesize, null);
            MyFansDAL mfd = new MyFansDAL();
            PagingDataSet pds;
            pds = mfd.GetMyFans(pagpar, uid, key ?? null, false);
            if (pds==null)
            {
                return "";
            }
            DataTable dt = pds.DataSet.Tables[0];
            StringBuilder stb = new StringBuilder();
            UserFansListINfo ufli = new UserFansListINfo();
            ufli.Total = pds.Capacity.ToString();
            ufli.PageCount = Pagesize.ToString();
            ufli.PageIndex = currpage.ToString();

            List<FansInfo> lfi = new List<FansInfo>();
            foreach (DataRow dr in dt.Rows)
            {
                FansInfo fi = new FansInfo();
                fi.fansuid = dr["FANSUID"].ToString();
                fi.fansname = dr["FANSNAME"].ToString();
                fi.proimg = dr["FANSPROIMAGE"].ToString();
                fi.avatar = dr["FANSAVATAR"].ToString();
                lfi.Add(fi);
            }
            ufli.lmfm = lfi;
            lasXML lx = new lasXML();
            lx.ufli = ufli;
            using (StringWriter sw = new StringWriter())
            {
                XmlSerializer xz = new XmlSerializer(lx.GetType());
                xz.Serialize(sw, lx);
                return sw.ToString();
            }


        }

        #region 暂时不用
        /// <summary>
        /// 关注
        /// </summary>
        /// <param name="uid"></param>
        private void CreatFriendShip(string fav_act,string fav_off)
        {
            Weiboinfo wb=Session["weibo"] as Weiboinfo;
            if (fav_act=="1")
            {
                string act_uid = "2393053602";
                Microblog_v2.Follow(wb.WeiboToken, Convert.ToInt64(act_uid));
            }
            if (fav_act=="1")
            {
               // string off_uid = "2393053602";
               // Microblog_v2.Follow(wb.WeiboToken, Convert.ToInt64(off_uid));
            }
            
        }
        private void  sendVbo(string strValue)
        {
            Weiboinfo wb=Session["weibo"] as Weiboinfo;
            UpdateStatusInfo upsi = new UpdateStatusInfo();
            upsi.Status = strValue;
            Microblog_v2.PostStatus(wb.WeiboToken, upsi);
        }
        #endregion

        /// <summary>
        /// 发送微博
        /// </summary>
        /// <param name="stre"></param>
        private void GXML(Stream stre)
        {         
            //            <root>
            //    <content id="1402315857" fav_official="1"
            //     fav_activity="1" value="去发地" />
            //</root>
            //XmlDocument xmldoc = new XmlDocument();
            //xmldoc.Load(stre);
            // xmldoc.Save(Path.Combine(Server.MapPath("/xmlF/"), Guid.NewGuid().ToString() + ".xml"));

            //var str =
            //    @"<root>  <content id='2393053602' fav_official='1' fav_activity='1' value='asasasasasdasdasd' /></root>";
            try
            {
            
                XmlReader reader = new XmlTextReader(stre);
                XDocument xdoc = XDocument.Load(reader);
                var sendWeiboMd = (from lv in xdoc.Descendants("content")
                                   select new SendWeiboMd
                                              {
                                                  ID = lv.Attribute("id").Value,
                                                  fav_official = lv.Attribute("fav_official").Value,
                                                  fav_activity = lv.Attribute("fav_activity").Value,
                                                  value = lv.Attribute("value").Value


                                              }).ToList().FirstOrDefault();
                if (sendWeiboMd != null)
                {
                    Weiboinfo wb = Session["weibo"] as Weiboinfo;

                    #region 测试用的
                    //OAuthAccessToken_v2 oAuth = new OAuthAccessToken();
                    //oAuth.Token = "2.00r4PQvCwUCZUBfa145ad162wJ53oB";
                    //oAuth.UserID = "2678389203";
                    //Weiboinfo wb = new Weiboinfo();
                    //wb.WeiboToken = oAuth;
                    //wb.WeiboUID = "2678389203";

                    //OAuthAccessToken_v2 oAuth1 = new OAuthAccessToken();
                    //oAuth.Token = "2.00r4PQvCwUCZUBfa145ad162wJ53oB";
                    //oAuth.UserID = "2678389203";
                    #endregion
                    
                    if (sendWeiboMd.fav_official == "1")
                    {
                        var favOfficial = ConfigurationManager.AppSettings["fav_official"];
                        try
                        {
                            Microblog_v2.Follow(wb.WeiboToken, Convert.ToInt64(favOfficial));
                        }
                        catch { }
                    }
                    if (sendWeiboMd.fav_activity == "1")
                    {
                        var favActivity = ConfigurationManager.AppSettings["fav_activity"];
                        try
                        {
                            Microblog_v2.Follow(wb.WeiboToken, Convert.ToInt64(favActivity));
                        }
                        catch { }
                    }
                    //关注官方微博
                    
                    UpdateStatusWithPicInfo upsi = new UpdateStatusWithPicInfo();
                  // UpdateStatusInfo upsi = new UpdateStatusInfo();
                    upsi.Status = sendWeiboMd.value;
                    upsi.Pic = Server.MapPath("/") + ConfigurationManager.AppSettings["sendimgurl"];
                    StatusInfo statusInfo = Microblog_v2.PostStatusWithPic(wb.WeiboToken, upsi);


                    //关注活动微博
                    

                    Response.Write(statusInfo!=null?"1":"0");


                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 测试用的
        public void test()
        {
            OAuthAccessToken_v2 oAuth=new OAuthAccessToken();
            oAuth.Token = "2.00kYAxbCwUCZUB0fa743b0e5gYyQAC";
            oAuth.UserID = "2393053602";
            Weiboinfo info = new Weiboinfo();
            info.WeiboToken = oAuth;
            info.WeiboUID = oAuth.UserID;
            info.IsHavenLg = true;
            Session["weibo"] = info;
            //UpdateStatusInfo upsi = new UpdateStatusInfo();
            //upsi.Status = "我要测试啊";

            //Microblog_v2.PostStatus(oAuth, upsi);
        }
        #endregion

        

    }
}